var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var md5 = require('md5');

var responseData;
var config = require('../config/config.js');
var db = mysql.createPool({ host: config.host, user: config.user, password: config.password, database: config. database})


router.use(function(req, res, next) {
    responseData = {
        code: 0,
        message: ''
    }
    next()
})



router.get('/', function(req, res, next) {
    res.render('admin/login');
})

router.post('/', function(req, res, next) {
    var username = req.body.username;
    var password = req.body.password;

    if (username == '') {
        // res.redirect('login');
        responseData.code = -1;
        responseData.message = '用户名不能为空';
        res.json(responseData);
        return;
    }
    if (password == '') {
        responseData.code = -2;
        responseData.message = '密码不能为空';
        res.json(responseData);
        return;
    }

    password = md5(password);

    db.query(`SELECT * FROM zq_user WHERE username ='${username}'`, function(err, data) {
        if (err) {
            responseData.code = -3;
            responseData.message = '数据库开小差啦';
            res.json(responseData);
            console.log(err)
            return;
        } else {
            console.log(data)
            if (data.length) {
                if (data[0].password == password) {
                    responseData.message = '登录成功';
                    req.session.user = {
                        id: data[0].id,
                        username: data[0].username,
                        isAdmin: data[0].isAdmin
                    }
                    // res.render('admin/index');
                    res.json(responseData);
                    // res.redirect('/admin')
                } else {
                    responseData.code = -4;
                    responseData.message = '密码错误';
                    res.json(responseData);
                    return;
                }
            } else {
                responseData.code = -5;
                responseData.message = '该用户不存在';
                res.json(responseData);
                return;
            }
        }
    })
})

module.exports = router